import { Component, createSignal, For, onMount, Show } from 'solid-js';

import logo from './logo.svg';
import styles from './App.module.css';
import { calcExpr } from './calc';

const App: Component = () => {

  const [userExpr, setUserExpr] = createSignal("");
  const [utoolsEnable, enableUTools] = createSignal(false)
  const [mode, setMode] = createSignal("");
  const [formats, setFormats] = createSignal([
    { id: "none", desc: "不使用" },
    { id: "cn", desc: "千万亿" },
    { id: "cn:1", desc: "千万亿" },
    { id: "en", desc: "KMGT" },
    { id: "en:1", desc: "KMGT" },
  ])


  onMount(async () => {
    let utools : UTools = window["utools"] as UTools;
    if (utools !== undefined) {
      utools.onPluginReady( () => {
        //utools.setSubInput((e) => setUserExpr(e.text), "100M+10K", true);
      });
      enableUTools(true);
    }
    document.addEventListener("keyup", (e) => {
      if (e.altKey) {
        try{
          let n = Number(e.key) - 1;
          const fmts = formats();
          if (n >= 0 && n < fmts.length) {
            let text = userExpr + ' = ' + calcExpr(userExpr(), mode(), fmts[n].id)
            navigator.clipboard.writeText(text).catch((e) => {
              console.error(e);
              utools?.copyText(text);
            });
          }
        }
        catch(e) {
          console.error(e)
        }
      }
    })
	});

  return (
    <div class={styles.App}>
      <input
        size="60"
        placeholder='100M + 10K'
        onInput={(e) => setUserExpr(e.currentTarget.value)}
        autofocus
      />
      <Show when={userExpr().length > 0}>
        <For each={formats()}>{(fmt, i) =>
          <div class={styles.Result}>
            <div > {userExpr()} = {calcExpr(userExpr(), mode(), fmt.id)}</div>
            <div >Alt+{i()+1}</div>
          </div>
        }</For>
      </Show>
    </div>
  );
};

export default App;
